<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-logo">
        <img src="@/assets/sport.ico" alt="Logo" class="logo-image" />
      </div>
      <div class="login-title">智能体测管理系统</div>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" :placeholder="loginForm.type === 'admin' ? '用户名' : '学号'" prefix-icon="User" size="large" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="密码" prefix-icon="Lock" type="password" size="large" @keyup.enter="handleLogin" show-password />
        </el-form-item>
        <el-form-item prop="type" class="login-type">
          <el-radio-group v-model="loginForm.type">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="student">学生</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin" size="large" round>登 录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <div class="copyright">
    <p>Copyright © 2025 智能体测管理系统</p>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { setToken, setUserInfo } from '@/utils/auth'
import { login } from '@/api/user'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '20230001', // 默认为学生账号
  password: '123456',
  type: 'student'
})

const loginRules = {
  username: [
    { required: true, message: () => loginForm.type === 'admin' ? '请输入用户名' : '请输入学号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

// 监听用户类型变化，重新校验用户名字段并更新默认用户名
watch(() => loginForm.type, (newType) => {
  // 根据用户类型设置默认用户名
  loginForm.username = newType === 'admin' ? 'admin' : '20230001'

  if (loginFormRef.value) {
    // 只对用户名字段进行校验
    loginFormRef.value.validateField('username')
  }
})

const handleLogin = () => {
  loginFormRef.value.validate(async valid => {
    if (!valid) return

    loading.value = true

    try {
      const res = await login(loginForm)

      if (res.code === 200) {
        // 登录成功，跳转到相应页面
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        localStorage.setItem('loginTime', Date.now().toString())

        // 确保用户信息包含type字段
        const userInfo = {
          ...res.data,
          type: res.data.type || loginForm.type // 确保类型存在
        }
        setUserInfo(userInfo)

        // 根据用户类型跳转到不同页面
        if (userInfo.type === 'admin') {
          ElMessage({
            type: 'success',
            message: `欢迎回来，${userInfo.name || '管理员'}！`,
            duration: 3000
          })
          router.push('/admin/students')
        } else {
          ElMessage({
            type: 'success',
            message: `欢迎回来，${userInfo.name || '同学'}！`,
            duration: 3000
          })
          router.push('/student/announcements')
        }
      } else {
        // 登录失败，显示具体错误信息
        if (res.code === 401 || res.code === 403) {
          ElMessage.error('用户名或密码错误')
        } else {
          ElMessage.error(res.message || '登录失败，请稍后重试')
        }
      }
    } catch (error) {
      // 网络请求失败的错误处理
      if (error.response) {
        // 服务器返回了错误状态码
        if (error.response.status === 401 || error.response.status === 403) {
          ElMessage.error('用户名或密码错误')
        } else if (error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('登录失败，请稍后重试')
        }
      } else if (error.request) {
        // 请求发出但没有收到响应
        ElMessage.error('服务器无响应，请检查网络连接')
      } else {
        // 请求设置出错
        ElMessage.error('登录请求错误，请稍后重试')
      }
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('@/assets/background.jpg') no-repeat center center;
  background-size: cover;
  position: relative;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 1;
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 2;
  animation: fadeIn 0.8s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-logo {
  text-align: center;
  margin-bottom: 10px;
}

.logo-image {
  width: 60px;
  height: 60px;
}

.login-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #1890ff;
  letter-spacing: 1px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  margin-top: 10px;
}

.login-type {
  text-align: center;
  margin-bottom: 5px;
}

.login-footer {
  text-align: center;
  font-size: 12px;
  color: #606266;
  margin-top: 20px;
}

.copyright {
  position: fixed;
  bottom: 10px;
  left: 0;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  z-index: 5;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
</style>